from django.shortcuts import render
from common.views import LoginRequiredJSONMixin
from django.views import View
from apps.orders.models import OrderInfo
from django.http import JsonResponse
from alipay import AliPay
from meiduo_mall import settings
from apps.payment.models import Payment


# Create your views here.

class PayURLView(LoginRequiredJSONMixin,View):
    def get(self,request,order_id):
#根据订单id查询信息，创建支付宝实例，调用支付宝网站支付方式生成order_string
#支付跳转连接 返回
        try:
            order=OrderInfo.objects.get(order_id=order_id,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'],user=request.user)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'无此订单'})



        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=True
        )
        subject='测试订单'
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
            notify_url=''
        )

        alipay_url='https://openapi.alipay.com/gateway.do?' + order_string

        return JsonResponse({'code':0,'alipay_url':alipay_url})


class PayStatusView(View,LoginRequiredJSONMixin):
    def put(self,request):
        # 1. 支付回调参数查询字符串  移除获取sign, 创建支付实例对象，调verify验证
#获取支付流水号，保存订单id和交易流水   修改订单状态 返回
        data=request.GET.dict()
        signature = data.pop('sign') #移除获取sign

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=True)

        success=alipay.verify(data,signature)

        trade_no=data.get('trade_no')
        out_trade_no=data.get('out_trade_no')

        Payment.objects.create(order_id=out_trade_no,trade_id=trade_no)
        OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
        return JsonResponse({'code':0,'trade_id':trade_no})























